#include <stdio.h>
#include "cutrace.h"
#include <stdlib.h>
#include <string.h>

void loadfield(double field[Nx*Ny], const char* str)
{
    int i = 0;
    int j = 0;
    FILE *fp = NULL;
    char *line,*record;
    char buffer[20450];
    if((fp = fopen(str, "r")) != NULL)
    {
        //printf("file open success:%s\n",str);
        while ((line = fgets(buffer, sizeof(buffer), fp))!=NULL)
        {
            record = strtok(line, ",");
            while (record != NULL)  
            {
                field[i*Ny+j++] = atof(record);
                record = strtok(NULL, ",");
            }
            i++; j = 0;
        }
        fclose(fp);
        fp = NULL;
        //printf("file close success:%s\n",str);
    }
}

void output(vec* vparr, vec* vvarr, double*vfreq, int N, const char* str)
{
    FILE *fp = NULL;
    if((fp = fopen(str, "w")) != NULL)
    {
    for(int i = 0; i < N; i++)
    {
        vec vp = vparr[i];
        vec vv = vvarr[i];
        double freq = vfreq[i];
        fprintf(fp,"%lf,%lf,%lf,",vp.x,vp.y,vp.z);
        fprintf(fp,"%lf,%lf,%lf,",vv.x,vv.y,vv.z);
        fprintf(fp,"%lf", freq);
        fprintf(fp,"\n");
    }
    fclose(fp);
    fp = NULL;
    printf("write particle success\n");
    }
}

vec cross(vec a, vec b)
{
    vec c = {0.0,0.0,0.0};
    c.x = a.y*b.z - a.z*b.y;
    c.y = a.z*b.x - a.x*b.z;
    c.z = a.x*b.y - a.y*b.x;
    return c;
}

double dot(vec a, vec b)
{
    return a.x*b.x + a.y*b.y+a.z*b.z;
}

vec operator+(vec a, vec b)
{
    vec c = {0.0,0.0,0.0};
    c.x = a.x + b.x;
    c.y = a.y + b.y;
    c.z = a.z + b.z;
    return c;
}

vec operator*(double a, vec x)
{
    vec y = {0.0, 0.0, 0.0};
    y.x = a*x.x;
    y.y = a*x.y;
    y.z = a*x.z;
    return y;
}